package com.blame.springblog.common.advice;


import com.blame.springblog.pojo.response.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;
    //对所有的controller方法执行，因为已经设置为true
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    //在controller返回数据后，在执行这个方法后返回响应体
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果返回了String类型，进行封装
        if(body instanceof String){
            return objectMapper.writeValueAsString(Result.success(body));
        }
        //如果直接返回了Result类型，直接返回，避免重复的包装
        if(body instanceof Result){
            return body;
        }
        return Result.success(body);
    }
}
